package MCQReaderInterface;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.tree.DefaultMutableTreeNode;

import MCQReaderModel.*;

public class MCQReaderButtons extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JButton validate;

	private JComboBox type;

	private JComboBox groupe;

	private JButton newGroup;

	private JTextField nbQuestion;

	private JButton scale;

	private JButton delete;

	private int question_counter = 0;

	private int codeBarreSize = 0;

	MCQReaderButtons() {
		super(new GridLayout(3, 2));
		String elementNames[] = { "Radios", "Cases", "Bit field", "Text area" };
		String noSelection[] = { "No Question" };
		type = new JComboBox(elementNames);
		groupe = new JComboBox(new DefaultComboBoxModel(noSelection));

		groupe.addItemListener(new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent e) {
				scale.setEnabled(!MCQReaderLayer.aGroupIsScalled()
						&& getGroupeSelected() != 0);
			}
		});

		validate = new JButton("validate");

		validate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				MCQReaderLayer qlc = MainInterface.thisIsIt.getRightFrame()
						.getPdfCalque();
				boolean isGood = true;
				if (qlc.isSelected()) {
					if (getTypeSelected() == 2) {
						isGood = false;
						String reponse = JOptionPane.showInputDialog(
								"Code Barre size?", Integer
										.toString(codeBarreSize));

						try {
							codeBarreSize = Integer.parseInt(reponse);
							isGood = true;
						} catch (Exception e1) {
							if (reponse != null)
								JOptionPane.showMessageDialog(null,
										"Invalib size of code barre!!! ",
										"Attention",
										JOptionPane.INFORMATION_MESSAGE, null);
						}
					}
					if (isGood) {
						PageNode node = MainInterface.thisIsIt.getLeftFrame()
								.getTree().currentNodePage();
						addToNode(node, qlc);

						MainInterface.thisIsIt.getLeftFrame().getTree().mainTree
								.updateUI();
						MainInterface.thisIsIt.getLeftFrame().getTree().mainTree
								.treeDidChange();
						MainInterface.thisIsIt.getRightFrame()
								.getPdfSelections().repaint();
					}
				}

			}
		});

		newGroup = new JButton("New Question");

		newGroup.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				PageNode pageNode = MainInterface.thisIsIt.getLeftFrame()
						.getTree().currentNodePage();
				DefaultMutableTreeNode node = null;
				switch (getTypeSelected()) {
				case 0: // radios is selected
					node = pageNode.getRadioNode();
					node.add(new RadioGroup(++question_counter));
					break;
				case 1: // cases is selected
					node = pageNode.getCaseNode();
					node.add(new CaseGroup(++question_counter));
					break;
				}
				nbQuestion.setText(Integer.toString(question_counter + 1));
				checkGroups(node);
				MainInterface.thisIsIt.getLeftFrame().getTree().mainTree
						.updateUI();
				MainInterface.thisIsIt.getLeftFrame().getTree().mainTree
						.treeDidChange();
				scale.setEnabled(true);
				repaint();
			}
		});

		type.addItemListener(new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent e) {
				checkGroups();
				if (e.getItem() == "Radios" || e.getItem() == "Cases") {
					groupe.setEnabled(true);
					scale.setEnabled(true);
					newGroup.setEnabled(true);
					nbQuestion.setEnabled(true);
					remove(0);
					add(scale, 0);
					scale.setEnabled(!MCQReaderLayer.aGroupIsScalled()
							&& getGroupeSelected() != 0);
				} else {
					groupe.setEnabled(false);
					scale.setEnabled(false);
					newGroup.setEnabled(false);
					nbQuestion.setEnabled(false);
					remove(0);
					add(validate, 0);
				}
			}
		});

		scale = new JButton("scale");
		scale.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (getTypeSelected() == 0 /* Radios */
						|| getTypeSelected() == 1 /* Cases */) {
					MCQReaderLayer qlc = MainInterface.thisIsIt.getRightFrame()
							.getPdfCalque();
					if (qlc.isSelected()) {
						if (getGroupeSelected() != 0) {
							PageNode pageNode = MainInterface.thisIsIt
									.getLeftFrame().getTree().currentNodePage();
							GroupNode node;
							if (getTypeSelected() == 0)/* Radios */
								node = (GroupNode) pageNode.getRadioNode()
										.getChildAt(getGroupeSelected() - 1);
							else
								/* Cases */
								node = (GroupNode) pageNode.getCaseNode()
										.getChildAt(getGroupeSelected() - 1);
							node.setHeight(qlc.getSelection().height);
							node.setWidth(qlc.getSelection().width);
							MainInterface.thisIsIt.getLeftFrame().getTree().mainTree
									.updateUI();
							MainInterface.thisIsIt.getLeftFrame().getTree().mainTree
									.treeDidChange();
							scale.setEnabled(false);
							MainInterface.thisIsIt.getRightFrame()
									.getPdfCalque().resetSelection();
							MainInterface.thisIsIt.getRightFrame()
									.getPdfCalque().repaint();
						}
					}
				}
			}
		});

		delete = new JButton("delete");
		delete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				DefaultMutableTreeNode node = MainInterface.thisIsIt
						.getLeftFrame().getTree().selected;
				if (node != null
						&& (node instanceof Zone || node instanceof GroupNode)) {
					((DefaultMutableTreeNode) node.getParent()).remove(node);
					MainInterface.thisIsIt.getLeftFrame().getTree().selected = null;
					checkGroups();
					MainInterface.thisIsIt.getLeftFrame().getTree().mainTree
							.updateUI();
					MainInterface.thisIsIt.getLeftFrame().getTree().mainTree
							.treeDidChange();
					MainInterface.thisIsIt.getRightFrame().getPdfSelections()
							.repaint();
				}
			}
		});

		scale.setEnabled(false);
		this.add(scale);

		this.setVisible(true);
		this.add(type);
		this.add(groupe);
		this.add(newGroup);
		JPanel nbSelect = new JPanel();
		nbQuestion = new JTextField(3);
		nbQuestion.setEnabled(true);
		nbQuestion.setText("1");
		nbSelect.add(new JLabel("Next question"));
		nbQuestion.addKeyListener(new KeyAdapter() {
			public void keyTyped(KeyEvent e) {
				if (e != null && e.getKeyChar() >= '0' && e.getKeyChar() <= '9') {
					question_counter = Integer.parseInt(nbQuestion.getText()
							+ e.getKeyChar()) - 1;
					System.out.println(question_counter);
				}
			}
		});
		nbSelect.add(nbQuestion);
		this.add(nbSelect);
		this.add(delete);
		TitledBorder titled = new TitledBorder("Buttons");
		titled
				.setBorder(BorderFactory
						.createLineBorder(new Color(100, 155, 0)));
		this.setBorder(titled);

	}

	private GroupNode findGroup(DefaultMutableTreeNode node, int num) {

		if (node != null) {
			int nbGroup = node.getChildCount();
			for (int i = 0; i < nbGroup; i++) {
				GroupNode group = (GroupNode) node.getChildAt(i);
				if (group.getNumGroup() == num)
					return group;
			}
		}
		return null;
	}

	void addToNode(PageNode currentPageNode, MCQReaderLayer qlc) {
		switch (getTypeSelected()) {
		case 0: // radios is selected
			findGroup(currentPageNode.getRadioNode(), question_counter).add(
					new Radio(qlc.getSelectionClone()));
			break;
		case 1: // cases is selected
			findGroup(currentPageNode.getCaseNode(), question_counter).add(
					new Case(qlc.getSelectionClone()));
			break;
		case 2: // bit field is selected
			currentPageNode.getCodeNode().add(
					new BitField(qlc.getSelectionClone(), codeBarreSize));
			break;
		case 3: // text area is selected
			currentPageNode.getTextNode().add(
					new TextZone(qlc.getSelectionClone(), codeBarreSize));
			break;
		}
	}

	void checkGroups() {
		PageNode pageNode = MainInterface.thisIsIt.getLeftFrame().getTree()
				.currentNodePage();
		switch (getTypeSelected()) {
		case 0: // radios is selected
			checkGroups(pageNode.getRadioNode());
			break;
		case 1: // cases is selected
			checkGroups(pageNode.getCaseNode());
			break;
		default:
			checkGroups(null);
			break;
		}
	}

	void checkGroups(DefaultMutableTreeNode node) {
		int nbGroup = 0;
		if (node != null)
			nbGroup = node.getChildCount();
		String[] content = new String[nbGroup + 1];

		content[0] = "No Question";

		for (int i = 0; i < nbGroup; i++)
			content[i + 1] = ("Question " + ((GroupNode) node.getChildAt(i))
					.getNumGroup());

		DefaultComboBoxModel jcbm = new DefaultComboBoxModel(content);
		groupe.setModel(jcbm);
		groupe.setSelectedIndex(nbGroup);
		repaint();
	}

	public int getTypeSelected() {
		return type.getSelectedIndex();
	}

	public int getGroupeSelected() {
		return groupe.getSelectedIndex();
	}
}
